<template>
  <div class="content-area" >
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0 10px auto; display: flex; flex-direction: column; align-items: center;">

          <div style="display: flex; align-items: center;">
            <div>
              <h2>小区用户信息管理</h2>
            </div>


            <el-select
                v-model="value"
                placeholder="选择某一小区查看"
                size="large"
                style="width: 240px; margin-left: 10px;"
                @change="handleSelectChange"
            >
              <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
              />
            </el-select>
            <el-button
                type="primary"
                size="large"
                style="margin-left: 10px;"
                @click="clearSelection"
            >
              清空选择
            </el-button>
          </div>
          <div class="table-header-container">
            <div class="search-container">
              <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                <el-option label="按用户姓名查询" value="userName"></el-option>
                <el-option label="按手机号码查询" value="phone"></el-option>
                <el-option label="按用户类别查询" value="userType"></el-option>
                <el-option label="按是否禁用查询" value="freeze"></el-option>
              </el-select>
              <el-input v-model="searchQuery"
                        :placeholder="
                  searchOption === 'userType'? '1--业主，2--物业' :
                  searchOption === 'freeze'? '0--未禁用，1--禁用' :
                  '请输入查询关键词'
                "
                        class="search-input"></el-input>
              <el-button type="primary" @click="searchUser" class="search-button">查询</el-button>
            </div>

            <el-button type="primary" @click="handleCommunity">增加记录</el-button>
          </div>
          <table v-if="userForm && userForm.data && userForm.data.records.length > 0"
                 style="text-align: center; width: 100%; border-collapse: collapse;">
            <thead>
            <tr>
              <th style="width: 70px; height: 32px; border: 1px solid #eee;">用户id</th>
              <th style="width: 200px; height: 32px; border: 1px solid #eee;">账号</th>
              <th style="width: 170px; height: 32px; border: 1px solid #eee;">密码</th>
              <th style="width: 100px; height: 32px; border: 1px solid #eee;">姓名</th>
              <th style="width: 50px; height: 32px; border: 1px solid #eee;">性别</th>
              <th style="width: 50px; height: 32px; border: 1px solid #eee;">年龄</th>
              <th style="width: 200px; height: 32px; border: 1px solid #eee;">身份证</th>
              <th style="width: 200px; height: 32px; border: 1px solid #eee;">手机号码</th>
              <th style="width: 200px; height: 32px; border: 1px solid #eee;">邮箱</th>
              <th style="width: 50px; height: 32px; border: 1px solid #eee;">用户类型</th>
              <th style="width: 80px; height: 32px; border: 1px solid #eee;">禁用</th>
              <th style="width: 50px; height: 32px; border: 1px solid #eee;">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in userForm.data.records" :key="index" style="border: 1px solid #eee;">
              <td style="width: 70px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.id" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 200px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.account" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 170px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.password" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.name" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.sex" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.age" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td style="width: 200px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.identification" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 200px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.phone" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td style="width: 200px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.email" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 25px; border: 1px solid #eee;">
                <el-input v-model="item.userType" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td>
                <ElSwitch
                    v-model="item.disabled"
                    @change="toggleDisableStatus(item)"
                />
              </td>
              <td style="width: 50px; height: 25px; border: 1px solid #eee;">
                <div class="button-group">
                  <template v-if="!item.isEdit">
                    <el-button type="success" @click="saveItem(item)">修改记录</el-button>
                  </template>

                  <template v-if="item.isEdit&&userForm && userForm.data && userForm.data.records.some(item => item.isEdit)">
                    <el-button type="success" @click="handleSaveEdit">保存修改</el-button>
                    <el-button type="default" @click="handleCancelEdit" style="margin-left: 10px">取消修改</el-button>
                  </template>
                </div>
              </td>
            </tr>
            </tbody>
          </table>
          <div v-else-if="errorMessage">{{ errorMessage }}</div>
          <div v-else>暂无用户记录</div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="userForm && userForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[4, 6, 8]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="userForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>

    <el-dialog v-model="addDialogFormVisible" title="增加用户" width="500">
      <el-form :model="addForm">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="addForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="账号" :label-width="formLabelWidth">
          <el-input v-model="addForm.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="addForm.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-input v-model="addForm.sex" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="addForm.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="身份证号" :label-width="formLabelWidth">
          <el-input v-model="addForm.identification" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLabelWidth">
          <el-input v-model="addForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="用户类型" :label-width="formLabelWidth">
          <el-select v-model="addForm.userType" placeholder="请选择用户类型">
            <el-option label="业主" value="1"></el-option>
            <el-option label="物业" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { ElSwitch } from 'element-plus';

export default {
  data() {
    return {
      userName: localStorage.getItem('adminName') || '',
      userForm: {
        id: "",
        name: "",
        account: "",
        password: "",
        sex: "",
        age: "",
        identification: "",
        phone: "",
        email: "",
        communityId: this.communityId,
        userType: "",
        freeze: ""
      },
      userStatisticsPage: null,
      errorMessage: '',
      currentPage: 1,
      pageSize: 8,
      addDialogFormVisible: false,
      addForm: {
        name: "",
        account: "",
        password: "",
        sex: "",
        age: "",
        identification: "",
        phone: "",
        email: "",
        communityId: this.communityId,
        userType: "",
        freeze: ""
      },
      communityId: "",
      isEdit: false,
      editUser: null,
      originalInfo: null,
      searchQuery: '',
      deleteId: null,
      formLabelWidth: '120px',
      searchOption: '',
      showDialog: false,
      value: null,
      communityList: null
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    clearSelection() {
      // 清空选择
      this.value = null;
      this.communityId = "";
      // 重新加载默认数据
      this.fetchUserStatisticsPage();
    },
    handleSelectChange(value) {
      this.communityId = value;
      this.fetchUserStatisticsPage();
    },
    async fetchCommunityList() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/community/search', {
          headers: {
            Authorization: token
          }
        });
        console.log(response)
        this.communityList = response.data.data;
        console.log('this.community',this.communityList)
      } catch (error) {
        ElMessage.error('获取小区列表时出错：' + error.message);
      }
    },
    handleCommunity(){
      if(this.communityId) {
        this.addDialogFormVisible = true;
      }else{
        console.log('未选择小区，显示提示');
        ElMessage.info('请先选择小区')
      }
    },
    pageChange(url) {
      this.$router.push(url);
    },
    async fetchUserStatisticsPage() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/users/page';
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          communityId: this.communityId
        };
        if (this.searchOption === 'userName') {
          params.name = this.searchQuery;
        } else if (this.searchOption === 'phone') {
          params.phone = this.searchQuery;
        } else if (this.searchOption === 'userType') {
          params.userType = this.searchQuery;
        } else if (this.searchOption === 'freeze') {
          params.freeze = this.searchQuery;
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
        this.userForm = response.data;
        this.originalInfo = {...this.userForm };
        if (this.userForm && this.userForm.data && this.userForm.data.records) {
          this.userForm.data.records.forEach(user => {
            user.disabled = user.freeze === 1;
            user.isEdit = false; // 新增代码，为每个用户记录添加初始isEdit状态为false
          });
        }
      } catch (error) {
        ElMessage.error('获取用户记录失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchUserStatisticsPage();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchUserStatisticsPage();
    },
    async toggleDisableStatus(user) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.put(`/api/users/freeze/${user.id}`, null,{
          headers: {
            Authorization: token
          }
        });
        console.log(response)
        if (response.data.code === 200) {
          const userFormIndex = this.userForm.data.records.findIndex(item => item.id === user.id);
          if (userFormIndex!== -1) {
            this.userForm.data.records[userFormIndex].isEdit = false;
            this.userForm.data.records[userFormIndex].disabled = true; // 设置禁用状态
          }
          ElMessage.success('禁用用户成功');
        } else {
          ElMessage.error('禁用用户失败');
        }
        this.fetchUserStatisticsPage();
      } catch (error) {
        ElMessage.error('禁用状态更新失败，请稍后重试');
      }
    },
    handleConfirm() {
      this.confirmAdd();
    },
    async confirmAdd() {
      try {
        const token = localStorage.getItem('token');
        console.log(this.addForm.name)
        const response = await axios.post('/api/users/register',  null,{
          params:{
            name: this.addForm.name ,
            account: this.addForm.account,
            password: this.addForm.password,
            sex: this.addForm.sex,
            age: this.addForm.age,
            identification: this.addForm.identification,
            phone: this.addForm.phone,
            email: this.addForm.email,
            communityId: this.communityId,
            userType: this.addForm.userType
          }
        });
        console.log(response.data)
        if (response.data.code === 200) {
          ElMessage.success('增加用户记录成功');
          this.addDialogFormVisible = false;
          this.fetchUserStatisticsPage();
        } else {
          ElMessage.error('增加用户记录失败,请输入正确信息');
        }
      } catch (error) {
        ElMessage.error('增加用户记录时出错：' + error.message);
      }
    },
    saveItem(user) {
      if (user.disabled) {
        ElMessage.error('该用户已被禁用，无法修改');
        return;
      }
      user.isEdit = true;
      const userIndex = this.userForm.data.records.findIndex(item => item.id === user.id);
      if (userIndex!== -1) {
        this.userForm.data.records[userIndex].isEdit = true;
        this.editUser = user;
        this.originalInfo = {...this.userForm };
      }
    },
    async handleSaveEdit() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          throw new Error('token不存在');
        }
        if (!this.editUser) {
          ElMessage.error('未找到当前编辑的用户记录');
          return;
        }
        const userIndex = this.userForm.data.records.findIndex(item => item.id === this.editUser.id);
        if (userIndex!== -1) {
          const updatedUser = this.userForm.data.records[userIndex];
          const response = await axios.put(
              `/api/users/updateUser`, null,
              {
                headers: {
                  Authorization: token,
                  'Content-Type': 'application/json'
                },
                params: {
                  id: updatedUser.id,
                  name: updatedUser.name,
                  account: updatedUser.account,
                  password: updatedUser.password,
                  sex: updatedUser.sex,
                  age: updatedUser.age,
                  identification: updatedUser.identification,
                  phone: updatedUser.phone,
                  email: updatedUser.email,
                  communityId: this.communityId,
                  userType: updatedUser.userType
                }
              }
          );
          if (response.data.code === 200) {
            this.fetchUserStatisticsPage();
            updatedUser.isEdit = false;
            ElMessage.success('用户信息修改成功');
          } else {
            ElMessage.error(`用户信息修改失败: ${response.data.msg}`);
          }
        }
      } catch (error) {
        if (error.response) {
          ElMessage.error(`用户信息修改时出错: ${error.response.data.msg}`);
        } else if (error.request) {
          ElMessage.error('用户信息修改时出错: 没有收到服务器响应');
        } else {
          ElMessage.error(`用户信息修改时出错: ${error.message}`);
        }
      }
    },
    handleCancelEdit() {
      if (this.editUser) {
        const userIndex = this.userForm.data.records.findIndex(item => item.id === this.editUser.id);
        if (userIndex!== -1) {
          this.userForm.data.records[userIndex].isEdit = false;
        }
      }
      this.isEdit = false;
    },
    async searchUser() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'userName') {
          const response = await axios.get('/api/users/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              name: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.userForm = response.data;
            this.originalInfo = {...this.userForm };
            if (this.userForm && this.userForm.data && this.userForm.data.records) {
              this.userForm.data.records.forEach(user => {
                user.disabled = user.freeze === 1;
              });
            }
          } else {
            ElMessage.error('查询用户信息失败，请输入正确信息');
          }
        } else if (this.searchOption === 'phone') {
          const response = await axios.get('/api/users/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              phone: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.userForm = response.data;
            this.originalInfo = {...this.userForm };
            if (this.userForm && this.userForm.data && this.userForm.data.records) {
              this.userForm.data.records.forEach(user => {
                user.disabled = user.freeze === 1;
              });
            }
          } else {
            ElMessage.error('查询用户信息失败，请输入正确信息');
          }
        } else if (this.searchOption === 'userType') {
          const response = await axios.get('/api/users/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              userType: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.userForm = response.data;
            this.originalInfo = {...this.userForm };
            if (this.userForm && this.userForm.data && this.userForm.data.records) {
              this.userForm.data.records.forEach(user => {
                user.disabled = user.freeze === 1;
              });
            }
          } else {
            ElMessage.error('查询用户信息失败，请输入正确信息');
          }
        }else if (this.searchOption === 'freeze') {
          const response = await axios.get('/api/users/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              freeze: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.userForm = response.data;
            this.originalInfo = {...this.userForm };
            if (this.userForm && this.userForm.data && this.userForm.data.records) {
              this.userForm.data.records.forEach(user => {
                user.disabled = user.freeze === 1;
              });
            }
          } else {
            ElMessage.error('查询用户信息失败，请输入正确信息');
          }
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchUserStatisticsPage();
    this.fetchCommunityList();
  }
};
</script>

<style scoped>
.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #eee;
  padding: 8px;
}

.container-style {
  height: 100%;
}

.header-style {
  background-color: rgb(204, 225, 234);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-style {
  text-align: center;
  background-color: rgba(129, 175, 184, 0.83);
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.menu-header {
  padding: 0;
}

.button-group {
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-input {
  flex: 1;
  width: 300px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.disabled-style {
  cursor: default;
}

.form-label-width {
  width: 120px;
}

.normal-input-color {
  color: inherit;
}

.edit-input-color {
  color: #ccc;
}

.community-select-wrapper {
  display: flex;
  align-items: center;
}
</style>